// pages/certification/certification.js
const md = require('../../utils/md5.js');
const app = getApp();
const post = require('../../utils/post.js');
var util = require('../../utils/util.js');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    array: ['请选择', '美国', '中国', '巴西', '日本'],
    index: 0,
    region: ['福建省', '厦门市', '思明区'],
    areatag: 0,
    bankarray: [{
      name: '请选择支行',
      id: '1'
    }],
    bankindex: 0,
    showbanks: "请选择支行"
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    var that = this;
    that.setlocal();
    var time = util.formatTime(new Date());
    time = time.split(' ')[0];
    time = time.split('-');
    that.setData({
      year: time[0],
      month: time[1],
      day: time[2],
    })
  },

  onShow: function() {
    var show = wx.getStorageSync('bankname');
    var showbanks = wx.getStorageSync('cbankname');
    var bankscode = wx.getStorageSync('cbankno');
    if (show) {
      this.setData({
        show: show
      })
    }
    if (showbanks) {
      this.setData({
        showbanks: showbanks
      })
    }
    if (bankscode) {
      this.setData({
        bankscode: bankscode
      })
    }
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {
    if (this.data.userinfo.BankName) {
      this.setData({
        show: this.data.userinfo.BankName
      })
    } else {
      this.setData({
        show: this.data.array[0]
      })
    }
  },
  bindRegionChange: function(e) {
    console.log('picker发送选择改变，携带值为', e.detail.value)
    this.setData({
      region: e.detail.value,
      showarea: e.detail.value[0] + "/" + e.detail.value[1] + "/" + e.detail.value[2],
      province: e.detail.value[0],
      city: e.detail.value[1],
      area: e.detail.value[2],
      areatag: 1
    })
    // this.getbanks(e.detail.value[1])
  },
  bindBankChange: function(e) {
    console.log('picker发送选择改变，携带值为', e.detail.value)
    this.setData({
      bankindex: e.detail.value,
      showbanks: this.data.bankarray[e.detail.value].name,
      bankscode: this.data.bankarray[e.detail.value].id
    })
  },
  getbanks: function(cityname = '', isfirst = 0) {
    var that = this;
    if (!cityname) {
      cityname = this.data.city;
    }
    if (isfirst == 1) {
      if (that.data.userinfo.CityName) {
        cityname = that.data.userinfo.CityName;
      } else {
        wx.showModal({
          title: '提示',
          content: '请先选择地区，否则无法选择支行信息！',
        })
        return;
      }
    }
    if (this.data.show == '请选择') {
      wx.showModal({
        title: '提示',
        content: '请先选择开户银行！',
      })
      return;
    }
    var datas = {};
    datas.where = "CityName =" + cityname + " and BankName like '%" + this.data.show + "%'";
    var datacall = function(res) {
      console.log(res);
      if (res.data.data.length > 0) {
        var banklist = [];
        var ll = {};
        for (var i = 0; i < res.data.data.length; i++) {
          ll.name = res.data.data[i].CBankName;
          ll.id = res.data.data[i].CBankNo;
          banklist.push(ll);
          ll = {};
        }
        that.setData({
          bankarray: banklist
        })
      }
    }
    var res2 = post.getdata("/BO/BA_BankDetail/Query", datas, datacall);
  },
  setlocal: function() {
    var that = this;
    that.setData({
      userinfo: wx.getStorageSync('userinfo')
    })
    if (that.data.userinfo.IDFaceImgUrl) {
      that.setData({
        img1: that.data.userinfo.IDFaceImgUrl,
        idcardimg1: that.data.userinfo.IDFaceImgUrl
      })
    } else {
      that.setData({
        img1: '/images/plus.png'
      })
    };
    if (that.data.userinfo.IDBackImgUrl) {
      that.setData({
        img2: that.data.userinfo.IDBackImgUrl,
        idcardimg2: that.data.userinfo.IDBackImgUrl
      })
    } else {
      that.setData({
        img2: '/images/plus.png'
      })
    };
    if (that.data.userinfo.CardNoImgUrl) {
      that.setData({
        img3: that.data.userinfo.CardNoImgUrl,
        idcardimg3: that.data.userinfo.CardNoImgUrl
      })
    } else {
      that.setData({
        img3: 'http://eplus.zokoo.com.cn/upload/wallet/medish.png'
      })
    }
    if (that.data.userinfo.BankName) {
      that.setData({
        show: that.data.userinfo.BankName
      })
    } else {
      that.setData({
        show: that.data.array[0]
      })
    }
    if (that.data.userinfo.ProName) {
      that.setData({
        showarea: that.data.userinfo.ProName + "/" + that.data.userinfo.CityName + "/" + that.data.userinfo.AreaName
      })
    } else {
      that.setData({
        showarea: "请选择省市区",
        areatag: 1
      })
    }
    if (that.data.userinfo.BankDetail) {
      that.setData({
        showbanks: that.data.userinfo.BankDetail
      })
    }
    // this.getbanks('',1);
  },
  uuid() {
    var s = [];
    var hexDigits = "0123456789abcdef";
    for (var i = 0; i < 36; i++) {
      s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
    }
    s[14] = "4"; // bits 12-15 of the time_hi_and_version field to 0010
    s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1); // bits 6-7 of the clock_seq_hi_and_reserved to 01
    s[8] = s[13] = s[18] = s[23] = "";

    var uuid = s.join("");
    return uuid;
  },
  chooseimg1(e) {
    var that = this;
    wx.chooseImage({
      count: 1, // 默认9
      sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
      sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
      success: function(res) {
        // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
        var tempFilePaths = res.tempFilePaths;
        console.log(tempFilePaths);
        var apinameIsMeb = "/File/Upload";
        var timestamp = new Date().getTime();
        timestamp = parseInt(timestamp / 1000);
        var md5IsMeb = md.hexMD5(app.server.appid + timestamp + apinameIsMeb + app.server.appkey);
        wx.showLoading({
          title: '上传中...',
        })
        wx.uploadFile({
          url: app.server.url + apinameIsMeb, //仅为示例，非真实的接口地址
          filePath: tempFilePaths[0],
          name: 'file[]',
          method: 'POST',
          header: {
            'content-type': 'multipart/form-data'
          },
          formData: {
            "sign": md5IsMeb,
            "appid": app.server.appid,
            "tmsp": timestamp,
            "objID": 666,
            "file": that.data.year + "/" + that.data.month + "/" + that.data.day + "/" + new Date().getTime() + Math.ceil(Math.random() * 1000) + ".jpg"
          },
          success: function(res) {
            wx.hideLoading();
            var data = res.data;
            data = JSON.parse(data);
            console.log(data.data)
            if (data.data != '') {
              that.setData({
                img1: "http://eplus.zokoo.com.cn/upload/" + data.data,
                idcardimg1: "http://eplus.zokoo.com.cn/upload/" + data.data
              })
            }
          }
        })
      }
    })
  },
  chooseimg2(e) {
    var that = this;
    wx.chooseImage({
      count: 1, // 默认9
      sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
      sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
      success: function(res) {
        // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
        var tempFilePaths = res.tempFilePaths;
        console.log(tempFilePaths);
        var apinameIsMeb = "/File/Upload";
        var timestamp = new Date().getTime();
        timestamp = parseInt(timestamp / 1000);
        var md5IsMeb = md.hexMD5(app.server.appid + timestamp + apinameIsMeb + app.server.appkey);
        wx.showLoading({
          title: '上传中...',
        })
        wx.uploadFile({
          url: app.server.url + apinameIsMeb, //仅为示例，非真实的接口地址
          filePath: tempFilePaths[0],
          name: 'file[]',
          method: 'POST',
          header: {
            'content-type': 'multipart/form-data'
          },
          formData: {
            "sign": md5IsMeb,
            "appid": app.server.appid,
            "tmsp": timestamp,
            "objID": 666,
            "file": that.data.year + "/" + that.data.month + "/" + that.data.day + "/" + new Date().getTime() + Math.ceil(Math.random() * 1000) + ".jpg"
          },
          success: function(res) {
            wx.hideLoading();
            var data = res.data;
            data = JSON.parse(data);
            console.log(data.data)
            if (data.data != '') {
              that.setData({
                img2: "http://eplus.zokoo.com.cn/upload/" + data.data,
                idcardimg2: "http://eplus.zokoo.com.cn/upload/" + data.data
              })
            }
          }
        })
      }
    })
  },
  chooseimg3(e) {
    var that = this;
    wx.chooseImage({
      count: 1, // 默认9
      sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
      sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
      success: function(res) {
        // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
        var tempFilePaths = res.tempFilePaths;
        console.log(tempFilePaths);
        var apinameIsMeb = "/File/Upload";
        var timestamp = new Date().getTime();
        timestamp = parseInt(timestamp / 1000);
        var md5IsMeb = md.hexMD5(app.server.appid + timestamp + apinameIsMeb + app.server.appkey);
        wx.showLoading({
          title: '上传中...',
        })
        wx.uploadFile({
          url: app.server.url + apinameIsMeb, //仅为示例，非真实的接口地址
          filePath: tempFilePaths[0],
          name: 'file[]',
          method: 'POST',
          header: {
            'content-type': 'multipart/form-data'
          },
          formData: {
            "sign": md5IsMeb,
            "appid": app.server.appid,
            "tmsp": timestamp,
            "objID": 666,
            "file": that.data.year + "/" + that.data.month + "/" + that.data.day + "/" + new Date().getTime() + Math.ceil(Math.random() * 1000) + ".jpg"
          },
          success: function(res) {
            wx.hideLoading();
            var data = res.data;
            data = JSON.parse(data);
            console.log(data.data)
            if (data.data != '') {
              that.setData({
                img3: "http://eplus.zokoo.com.cn/upload/" + data.data,
                idcardimg3: "http://eplus.zokoo.com.cn/upload/" + data.data
              })
            }
          }
        })
      }
    })
  },
  bindPickerChange: function(e) {
    console.log('picker发送选择改变，携带值为', e.detail.value)
    this.setData({
      index: e.detail.value,
      show: this.data.array[e.detail.value]
    })
  },
  formSubmit: function(e) {
    var that = this;
    console.log('form发生了submit事件，携带数据为：', e.detail.value);
    if (e.detail.value.name == '') {
      wx.showModal({
        title: '',
        content: '姓名不能为空',
      })
      return;
    }
    if (e.detail.value.idcard == '') {
      wx.showModal({
        title: '',
        content: '身份证号不能为空',
      })
      return;
    }
    if (e.detail.value.bankname == '') {
      wx.showModal({
        title: '',
        content: '开户银行不能为空',
      })
      return;
    }
    if (e.detail.value.bankdetail == '' || e.detail.value.bankdetail == '请选择支行') {
      wx.showModal({
        title: '',
        content: '开户支行不能为空',
      })
      return;
    }
    if (e.detail.value.banknumber == '') {
      wx.showModal({
        title: '',
        content: '银行卡号不能为空',
      })
      return;
    }
    if (e.detail.value.idcardimg1 == '') {
      wx.showModal({
        title: '',
        content: '身份证正面还未上传',
      })
      return;
    }
    if (e.detail.value.idcardimg2 == '') {
      wx.showModal({
        title: '',
        content: '身份证反面还未上传',
      })
      return;
    }
    if (e.detail.value.idcardimg3 == '') {
      wx.showModal({
        title: '',
        content: '银行卡正面未上传',
      })
      return;
    }
    wx.showLoading({
      title: '正在提交...',
    })
    // 获取时间戳
    var apinameIsMeb = "/BO/BA_Member/Modify";
    var timestamp = new Date().getTime();
    timestamp = parseInt(timestamp / 1000);
    var md5IsMeb = md.hexMD5(app.server.appid + timestamp + apinameIsMeb + app.server.appkey);
    var data = {};
    data.MebID = (wx.getStorageSync('userinfo')).MebID;
    data.MebName = e.detail.value.name;
    data.PersonID = e.detail.value.idcard;
    data.BankName = e.detail.value.bankname;
    data.BankCardNo = e.detail.value.banknumber;
    data.IDFaceImgUrl = e.detail.value.idcardimg1;
    data.IDBackImgUrl = e.detail.value.idcardimg2;
    data.CardNoImgUrl = e.detail.value.idcardimg3;
    data.BankDetail = e.detail.value.bankdetail;
    if (that.data.bankscode) {
      data.CBankNo = that.data.bankscode;
    }
    if (that.data.province) {
      data.ProName = that.data.province;
      data.CityName = that.data.city ? that.data.city:"";
      data.AreaName = that.data.area ? that.data.area:"";
    }
    data._BOState = 10;
    data = JSON.stringify(data);
    console.log(data);
    wx.request({
      //后台接口地址
      url: app.server.url + apinameIsMeb,
      data: {
        sign: md5IsMeb,
        appid: app.server.appid,
        tmsp: timestamp,
        data: data
      },
      method: 'POST',
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      success: function(res) {
        wx.hideLoading();
        console.log(res);
        if (res.data.code == 0) {
          wx.navigateBack({
            delta: 1
          })
          // wx.switchTab({
          //   url: '/pages/mine/mine',
          // })
        } else {
          wx.showModal({
            title: '',
            content: res.data.msg,
          })
          console.log(res);
          return;
        }
      },
      fail:function(res){
        wx.hideLoading();
        wx.showModal({
          title: '',
          content: "请求失败",
        })
        console.log(res);
        return;
      }
    })

  },
  tobank: function() {
    wx.navigateTo({
      url: '/pages/bank/bank',
    })
  },
  tobankson: function() {
    var banknmame = this.data.show;
    if (banknmame == '请选择') {
      wx.showModal({
        title: '',
        content: '请先选择开户银行！',
      })
      return;
    }
    var city = this.data.city ? this.data.city : this.data.userinfo.CityName;
    if (!city) {
      wx.showModal({
        title: '',
        content: '请先选择开户地区！',
      })
      return;
    }
    wx.navigateTo({
      url: '/pages/bankson/bankson?bankname=' + banknmame + "&city=" + city,
    })
  }
})